package com.dpj.book.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dpj.book.pojo.Cart;
import com.dpj.book.pojo.User;
import com.dpj.book.service.CartItemService;
import com.dpj.book.service.UserService;
import com.dpj.book.service.impl.CartItemServiceImpl;
import com.dpj.book.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.util.PrimitiveIterator;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService=new UserServiceImpl();
    private CartItemService cartItemService=new CartItemServiceImpl();

    public void loginByUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置请求参数的中文乱码
        request.setCharacterEncoding("utf-8");
        User user = JSONObject.parseObject(request.getReader().readLine(), User.class);

        User user1=userService.selectByUser(user);
        if(user1!=null){
            HttpSession session = request.getSession();
            Cart cart = cartItemService.getCart(user1);
            user1.setCart(cart);
            session.setAttribute("user",user1);
            String uname = user1.getUname();
            Integer totalCount = user1.getCart().getTotalCount();
           // String s = "{\"code\":\"success\",\"username\":\"" + uname + "\"}";
            String s = "{\"code\":\"success\",\"userName\":\"" + uname + "\",\"totalCount\":\"" + totalCount + "\"}";
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(s);
        }else {
            response.getWriter().write("error");
        }
    }

}
